package com.gzyj.jtt808.v2011;

import com.gzyj.jtt808.utils.HexBytesUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.Data;

import java.io.Serializable;

/**
 * @author lhj
 */
@Data
public class HeaderMsgBodyProperty implements Serializable {

    private boolean isSubcontract;//是否分包

    private HeaderEncryptMethod encryptMethod;//加密方法

    private int dataLength;//消息体长度


    public ByteBuf encode() {
        ByteBuf buf = Unpooled.buffer(2);
        int tmpIsPacke = 0;
        if (this.isSubcontract) {
            tmpIsPacke = 1 << 13;
        }

        int tmpEncrypt;
        //  2.3.数据加密方式
        switch (this.encryptMethod) {
            case None:
                tmpEncrypt = 0;
                break;
            case RSA:
                tmpEncrypt = 1 << 10;
                break;
            default:
                tmpEncrypt = 0;
                break;
        }

        buf.writeShort(tmpIsPacke | tmpEncrypt | this.dataLength);
        return buf;
    }

    public HeaderMsgBodyProperty decode(byte[] in) {

        Short tmp = Short.parseShort(HexBytesUtil.bytesToHex(in), 16);

        this.isSubcontract = ((tmp >> 13) & 0x001) == 1;
        switch ((tmp & 0x400) >> 10) {
            case 0:
                this.encryptMethod = HeaderEncryptMethod.None;
                break;
            case 1:
                this.encryptMethod = HeaderEncryptMethod.RSA;
                break;
            default:
                this.encryptMethod = HeaderEncryptMethod.None;
                break;
        }
        this.dataLength = tmp & 0x3FF;

        return this;
    }

}
